package org.itboys.core.service.mongo.web;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.tray.SundayTrayMapper;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mongo.dispatch.SundayDispatchModel;
import org.itboys.core.entity.mongo.dispatch.SundayDispatchOrder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/12/14
 * @Description：web端调度单service
 */
@Service
public class SundayDispatchService extends BaseMongoService<SundayDispatchOrder> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayDispatchOrder> getEntityClass() {
        return SundayDispatchOrder.class;
    }

    @Autowired
    private SundayDispatchModelService modelService;
    @Autowired
    private SundayTrayMapper trayMapper;

    public void apply(Long id, SundayMember member, Long storeId, String storeName, List<SundayDispatchModel> models) {
        if(ListUtil.isNull(models)){
            throw new ErrorException(ExceptionEnum.DISPATCH_MODEL_EXCEPTION.getValue());
        }
        SundayDispatchOrder order = new SundayDispatchOrder();
        order.setApplyId(member.getId());
        order.setApplyName(member.getRealName());
        order.setApplyStoreId(storeId);
        order.setApplyStoreName(storeName);
        order.setState(SundayCommonConstants.dispatch_order_state_init);
        if (LongUtil.isNotZreo(id)) {
            super.updateExceptEmpty(id, order);
        } else {
            super.save(order);
        }
        modelService.save(order.getId(), models);
    }

    /**
     * 查询调度单
     * @param request
     * @param member
     * @param type
     * @return
     */
    public PageResult<SundayDispatchOrder> select(HttpServletRequest request, SundayMember member, Integer type) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request, "state");
        Map<String, String> vagueParam = ParamUtil.packageMongoVagueParam(request);
        param.put("isDeleted", SundayCommonConstants.NO);
        if (SundayCommonConstants.dispatch_select_type_own.equals(type)) {
            param.put("applyId", member.getId());
        } else if (SundayCommonConstants.dispatch_select_type_other.equals(type)) {
            param.put("acceptId", member.getId());
        }
        PageResult<SundayDispatchOrder> result = super.containpageQuery(request, vagueParam, param);
        List<SundayDispatchOrder> data = result.getData();
        result.setData(packModels(data));
        return result;
    }

    /**
     * 查询公共池未接单的调度单
     *
     * @param request
     * @param member
     * @return
     */
    public PageResult<SundayDispatchOrder> pool(HttpServletRequest request, SundayMember member) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request);
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("applyId !=", member.getId());
        param.put("state", SundayCommonConstants.dispatch_order_state_pass);
        PageResult<SundayDispatchOrder> result = super.pageQuery(request, param);
        List<SundayDispatchOrder> data = result.getData();
        result.setData(packModels(data));
        return result;
    }

    public List<SundayDispatchOrder> packModels(List<SundayDispatchOrder> data) {
        if (ListUtil.isNotNull(data)) {
            List<Long> orderIds = new ArrayList<>();
            for (SundayDispatchOrder o : data
                    ) {
                orderIds.add(o.getId());
            }
            Map<String, Object> param = new HashMap<>();
            param.put("isDeleted", SundayCommonConstants.NO);
            param.put("orderId in", orderIds);
            List<SundayDispatchModel> models = modelService.list(param);
            for (SundayDispatchOrder o : data
                    ) {
                List<SundayDispatchModel> _models = new ArrayList<>();
                for (SundayDispatchModel m : models
                        ) {
                    if (m.getOrderId().equals(o.getId())) {
                        _models.add(m);
                        continue;
                    }
                }
                o.setModels(_models);
            }
        }
        return data;
    }

    /**
     * 用户接单
     *
     * @param member
     * @param id
     */
    public void accept(SundayMember member, Long id) {
        if (member == null) throw new ErrorException(ExceptionEnum.USER_NONENTITY.getValue());
        SundayDispatchOrder order = super.getById(id);
        if(!SundayCommonConstants.dispatch_order_state_pass.equals(order.getState())){
            throw new ErrorException(ExceptionEnum.DISPATCH_STATE_EXCEPTION.getValue());
        }
        order.setAcceptId(member.getId());
        order.setAcceptName(member.getRealName());
        order.setState(SundayCommonConstants.dispatch_order_state_accept);
        super.updateExceptEmpty(id, order);
    }

    /**
     * 查询一个调度单下的模板需求
     *
     * @param request
     * @param id      调度单
     * @return
     */
    public PageResult<SundayDispatchModel> selectModels(HttpServletRequest request, Long id) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request, "state");
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", id);
        PageResult<SundayDispatchModel> result = modelService.pageQuery(request, param);
        return result;
    }

    public void saveTrays(Long orderId, Long orderModelId, List<Long> trayIds) {
        SundayDispatchModel model = new SundayDispatchModel();
        model.setState(SundayCommonConstants.YES);
        model.setTrayIds(trayIds);
        modelService.updateExceptEmpty(orderModelId, model);
        SundayDispatchOrder order = super.getById(orderId);
        Map<String, Object> param = new HashMap<>();
        //修改托盘的持有人，所属仓库
        param.put("serviceId", order.getApplyId());
        param.put("storeId", order.getApplyStoreId());
        trayMapper.batchUpdateFields(param, trayIds);
    }

    /**
     * 根据订单id获取托盘id集合
     * @param orderId
     * @return
     */
    public List<Long> getTrays(Long orderId) {
        Map<String, Object> param = new HashMap<>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", orderId);
        List<SundayDispatchModel> models = modelService.list(param);
        List<Long> trays = new ArrayList<>();
        if (ListUtil.isNotNull(models)) {
            for (SundayDispatchModel m : models
                    ) {
                if(ListUtil.isNotNull(m.getTrayIds())){
                    trays.removeAll(m.getTrayIds());
                    trays.addAll(m.getTrayIds());
                }
            }
        }
        return trays;
    }
}
